<?php
/**
 * AJAX Handler for Contrib: Search - Return a list of users based on the search
 * NOTE: This callback is limited to finding 35 users. This is to stop the entire database returning at once...
 * NOTE: The search length must be at least 5. This is to make it so less users are returned via a search. As for example 'a%' is potentially a lot of users!
 * NOTE: The search matches in SQL as $search% (anything starting with the search).
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    $_ECLIPSEMDE = array();
    
    // Disable Templating System
    $_ECLIPSEMDE['TEMPLATING'] = false;
    require_once('../../SiteIncludes.GLOBAL.php');
    
    // Tell libdebug to never print out error information - overrides debugging flags in fwork
    $_LIBDEBUG->silence();
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
    
    // Ensure all variables needed are set
    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false && isset($gVAR['alias']) !== false && isset($gVAR['user']) !== false) {
	try {
	    $Project =& $ProjectStash->get($gVAR['alias']);
	    
	    if($Project->userCanEdit($_LOGGEDINUSER->get_userid()) === true) {
		$safe_un = $sql_conx->real_escape_string($gVAR['user']);
		if(strlen($gVAR['user']) < 4) {
		    $js_extend = '';
		    $js_callparent = 'parent.EDJXConfirmer.show_nok(); parent.UserContribEDJX.searchUnderMinLength(true);';
		} else {
		    $query = $sql_conx->query("SELECT `uid`, `username` FROM `users` WHERE `username` LIKE '{$safe_un}%' LIMIT 35;");
		    $js_extend = '';
		    if($query->num_rows === 0) {
			$boolNone = 'true';
		    } else {
			$j_i = 0;
			while($row = $query->fetch_assoc()) {
			    $js_extend .= "ids[{$j_i}] = '{$row['uid']}';\n";
			    $js_extend .= "names[{$j_i}] = '{$row['username']}';\n";
			    $j_i++;
			}
			$boolNone = 'false';
		    }
		    $js_callparent = 'parent.UserContribEDJX.updateSearch(ids, names, '.$boolNone.'); parent.UserContribEDJX.searchUnderMinLength(false); parent.EDJXConfirmer.show_ok();';
		}
		echo <<<EOX
		    <!DOCTYPE html>
			<html>
			    <head><title></title></head>
			    <body>
				<script type="text/javascript">
				    var names = new Array();
				    var ids = new Array();
				    {$js_extend}
				    {$js_callparent}
				</script>
			    </body>
			</html>
EOX;
	    } else {
		throw new InvalidProjectException();
	    }
	} catch(InvalidProjectException $e) {
	    header("HTTP/1.1 400 Bad Request");
	    die($nok_caller);
	}
    } else {
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
    
?>